package com.niuwa.p2p.core.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.struts2.ServletActionContext;

public class FileUtil {
	
    final static int BUFFER_SIZE = 4096;  
	
	public static void writeFile(String filename, String content) throws IOException {
		if (StringUtil.isEmpty(filename)) {
			return;
		}
		File file = new File(filename);
		if (!file.exists()) {
			file.createNewFile();
		}
		Writer out = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(file), "UTF-8"));
		try {
			out.write(content);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
	}
	
	/**
	 * 检查上传文件是否存在
	 * 
	 * @param uploadedFileName
	 * @return
	 */
	public static boolean isFileUploadedExist(String uploadedFileName){
        try {        	
           	String storagePath = PropertiesUtil.getProperty("system.uploadFilePath");
	        if (!StringUtil.isEmpty(storagePath)) {	 
	          	// 文件保存的父目录  
		    	ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
		        String realpath = ServletActionContext.getServletContext().getRealPath(storagePath); 
	            // 利用父子目录穿件文件目录
	            File uploadedFile=new File(new File(realpath), uploadedFileName);            
	            if(!uploadedFile.exists()){  
	            	return false;
		        }
	        }
        } catch(IOException ioe) {
        	return false;
        }
        return true;
	}
	
	/**
	 * 获取上传文件路径
	 * 
	 * @return
	 */
	public static String getStoragePath(){
			return PropertiesUtil.getProperty("system.uploadFilePath");
		
	}
	public static String getPublicFilePath(){
		return PropertiesUtil.getProperty("system.publicFilePath");
	}
	
	
	/**
	 * 取得文件类型
	 * 没有类型返回空。
	 * 
	 * @param fileName 文件名
	 * @return 文件类型 
	 * 
	 */
	public static String getFileType(String fileName){
		String fileType = "";
		if(fileName.indexOf(".") == -1){
			return "";
		}
		String[] words = fileName.split("[.]");
		fileType = words[words.length - 1];
		return fileType;
	}
	
	/*
	 * 读取文件所有内容
	 */
	public static String readTotalFile(String fileName){
	    File file = new File(fileName);
	    BufferedReader reader= null;
	    StringBuilder sb = new StringBuilder();
	    try{
	        reader = new BufferedReader(new FileReader(file));
	        String line = null;
	        while((line = reader.readLine())!= null){
	            sb.append(line);
	        }
	    }catch(IOException e){
	        e.printStackTrace();
	    }finally{
	        if(reader != null){
	            try{
	                reader.close();
	            }catch(IOException el){
	                el.printStackTrace();
	            }
	        }
	    }
	    return sb.toString();
	}


    
    // 将InputStream转换成String  
    public static String inputStream2String(InputStream in) throws Exception {  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();    
        byte[] data = new byte[BUFFER_SIZE];    
        int count = -1;    
        while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)  {  
            outStream.write(data, 0, count);  
        }
        data = null;  
        outStream.close();
        return new String(outStream.toByteArray(), "UTF-8");  
    }  
  
    // 将InputStream转换成某种字符编码的String  
    public static String inputStream2String(InputStream in, String encoding)  
            throws Exception {  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] data = new byte[BUFFER_SIZE];  
        int count = -1;  
        while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
            outStream.write(data, 0, count);  
        }
        data = null;
        outStream.close();
        return new String(outStream.toByteArray(), encoding);  
    }  
  
    // 将String转换成InputStream  
    public static InputStream string2InputStream(String in) throws Exception {    
        ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes("UTF-8"));  
        return is;  
    }  
  
    // 将InputStream转换成byte数组  
    public static byte[] inputStream2Byte(InputStream in) throws IOException {    
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] data = new byte[BUFFER_SIZE];    
        int count = -1;    
        while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {  
        	outStream.write(data, 0, count);  
        }
        data = null;  
        outStream.close();
        return outStream.toByteArray();    
    }  
  
    // 将byte数组转换成InputStream  
    public static InputStream byte2InputStream(byte[] in) throws Exception {    
        ByteArrayInputStream is = new ByteArrayInputStream(in);    
        return is;    
    }  
  
    // 将byte数组转换成String  
    public static String byte2String(byte[] in) throws Exception {    
        InputStream is = byte2InputStream(in);    
        return inputStream2String(is);    
    } 
    
    // 将input转换成File
    public void inputStream2File(InputStream ins,File file) throws IOException{
	   OutputStream os = new FileOutputStream(file);
	   int bytesRead = 0;
	   byte[] buffer = new byte[8192];
	   while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
	      os.write(buffer, 0, bytesRead);
	   }
	   os.close();
	   ins.close();
	}
    
    /** 
     * 从网络Url中下载文件 
     * @param urlStr 
     * @param fileName 
     * @param savePath 
     * @throws IOException 
     */  
    public static void  httpUrl2File(String urlStr,String fileName,String savePath) throws IOException{  
        URL url = new URL(urlStr);    
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
        //设置超时间为3秒  
        conn.setConnectTimeout(3*1000);  
        //防止屏蔽程序抓取而返回403错误  
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
  
        //得到输入流  
        InputStream inputStream = conn.getInputStream();    
        //获取自己数组  
        byte[] getData = inputStream2Byte(inputStream);      
  
        //文件保存位置  
        File saveDir = new File(savePath);  
        if(!saveDir.exists()){  
            saveDir.mkdir();  
        }  
        File file = new File(saveDir+File.separator+fileName);      
        FileOutputStream fos = new FileOutputStream(file);       
        fos.write(getData);   
        if(fos!=null){  
            fos.close();    
        }  
        if(inputStream!=null){  
            inputStream.close();  
        }     
        System.out.println("info:"+url+" download success");     
    }     

}
